const { spawn } = require('child_process')
var log4js = require('log4js');
var os=require('os')

log4js.configure({  
  appenders: {  
      fileout: { type: "file", filename: "fileout.log" }, 
      datafileout: {
          type: "dateFile", 
          filename: "datafileout.log", 
          pattern: ".yyyy-MM-dd"
      },
      consoleout: { type: "console" }, 
  }, 
  categories: {    
      default: { appenders: ["fileout","consoleout"], level: "debug" },   
      anything: { appenders: ["consoleout"], level: "debug" }
  }
});

let logger = log4js.getLogger('default');
logger.debug(os.platform())
// const pythonScriptPath = 'cycle.py'
const pythonScriptPath='C:\\Users\\ldsb\\Documents\\NodejsProject\\test0\\server\\cycle.py'
_workprocess = spawn('python', [pythonScriptPath])
_sendObj = {
    operation: "",
    port: {
      address: 0,
      bit: 0
    }}

const readValue = callback => {
    logger.info('enter')
    // console.log('enter')
    _sendObj.operation = 'read'
    _sendObj.port.address = 0
    _sendObj.port.bit = 0
    var sendstr = JSON.stringify(_sendObj)
    sendstr = sendstr + '\n'
    //流输入
    logger.info(sendstr)
    _workprocess.stdin.write(sendstr, (err) => {
        if (!err)
            //流输出
            _workprocess.stdout.once('data', (data) => {
                // console.log(data.toString())
                try {
                    var recvObj = JSON.parse(data.toString())
                } catch (error) {
                    console.log(data.toString())
                    throw new Error('数据格式error')
                }
                callback(null, recvObj.value)
            })
        else
            console.log('wirte error: ', err)
    })
}

setInterval(() => {
    readValue((err, value) => {
        console.log('value: ', value)
    })
    // logger.info('xxxxx')
}, 500);